package com.zc.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.zc.common.MenuEnum;
import com.zc.po.Comployee;
import com.zc.po.Department;
import com.zc.po.Menu;
import com.zc.po.UserInfo;
import com.zc.po.ZcInfo;
import com.zc.po.ZcInout;
import com.zc.service.ComployeeService;
import com.zc.service.DepartmentService;
import com.zc.service.MenuService;
import com.zc.service.UserInfoService;
import com.zc.service.ZcInfoService;
import com.zc.service.ZcInoutService;
import com.zc.service.ZcWxService;

@Controller
public class CenterController {

	@Autowired
	private ComployeeService comployeeService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private ZcInfoService zcInfoService;
	@Autowired
	private ZcInoutService zcInoutService;
	@Autowired
	private ZcWxService zcWxService;

	@RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST })
	public String index() {
		return "login/login";
	}

	@RequestMapping(value = "/sysLogin")
	public String login(@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password, Model model, HttpSession session) {
		UserInfo ui = userInfoService.selectByPrimaryKey(username);
		if (ui != null && ui.getPwd().equals(password)) {
			session.setAttribute("username", ui.getUsername());
			session.setAttribute("code", ui.getComployeeNo());
			session.setAttribute("competence", ui.getCompetence());
			String menu[] = ui.getMenu().split(",");
			List<Menu> list = new ArrayList<Menu>();
			for (String m : menu) {
				list.add(menuService.selectByPrimaryKey(m));
			}
			session.setAttribute("menus", list);
//			TODO 此处修改 date: 0322
			return "redirect:/mainframe/layer-index.jsp";
		}
		model.addAttribute("err", "用户名或密码错误");
		return "login/login";
	}

	// 权限管理
	@RequestMapping(value = "/menu", method = { RequestMethod.GET, RequestMethod.POST })
	public String menu(Model model) {
		// 查询所有用户信息
		List<Comployee> dataList = comployeeService.selectAll();
		String jsonData = JSON.toJSONString(dataList);
		model.addAttribute("comployees", jsonData);
		return "admin/menu";
	}

	// 去修改权限页面
	@RequestMapping(value = "/findUserbyname", method = { RequestMethod.GET, RequestMethod.POST })
	public String findUserbyname(Model model, String comployeeNo) {
		// 查询所有用户信息
		Comployee comployee = comployeeService.selectByPrimaryKey(comployeeNo);
		model.addAttribute("comployee", comployee);
		// 查询权限列表
		if (comployee != null) {
//			UserInfo ui = userInfoService.selectByPrimaryKey(comployee.getComployeeName());
			UserInfo ui = userInfoService.selectByNo(comployee.getComployeeNo());

			if (!ObjectUtils.isEmpty(ui)) {
				model.addAttribute("mymenus", ui.getMenu());
			}

		}
		model.addAttribute("menus", menuService.selectAll());
		return "admin/menu_update";
	}

	// updateUserMenu
	@ResponseBody
	@RequestMapping(value = "/updateUserMenu", method = { RequestMethod.POST })
	public String updateUserMenu(Model model, @RequestBody Map<String, String> dataMap) {
		StringBuffer sb = new StringBuffer();
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu1.getK())) ? "" : dataMap.get(MenuEnum.Menu1.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu2.getK())) ? "" : dataMap.get(MenuEnum.Menu2.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu3.getK())) ? "" : dataMap.get(MenuEnum.Menu3.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu4.getK())) ? "" : dataMap.get(MenuEnum.Menu4.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu5.getK())) ? "" : dataMap.get(MenuEnum.Menu5.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu6.getK())) ? "" : dataMap.get(MenuEnum.Menu6.getK()))
				.append(",");
		sb.append(StringUtils.isEmpty(dataMap.get(MenuEnum.Menu7.getK())) ? "" : dataMap.get(MenuEnum.Menu7.getK()));
		String comployeeName = dataMap.get(MenuEnum.RequestEnum.RequestParm1.getK());
		// 真的牛B 根据用户名修改
		UserInfo ui = new UserInfo();
		ui.setUsername(comployeeName);
		ui.setMenu(sb.toString());
		userInfoService.updateByPrimaryKeySelective(ui);
		return "/menu";
	}

	// 用户列表
	@RequestMapping(value = "/user_list", method = { RequestMethod.GET, RequestMethod.POST })
	public String user_list(Model model) {
		// 查询所有用户信息
		List<Comployee> tableData = comployeeService.selectAll();
		model.addAttribute("comployees", JSON.toJSONString(tableData));
		return "employee/employee_list";
	}

	// 去添加员工 addEmployee
	@RequestMapping(value = "/addEmployee", method = { RequestMethod.GET, RequestMethod.POST })
	public String addEmployee(Model model) {
		model.addAttribute("departments", departmentService.selectAll());
		return "employee/employee_add";
	}

	// addEmployeeInfo
	@RequestMapping(value = "/addEmployeeInfo", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String addEmployeeInfo(Model model, @RequestBody Comployee comployee) {
		try {
			comployeeService.insertSelective(comployee);
		} catch (Exception e) {
			return "error";
		}
		return "/user_list";
	}

	// 去编辑员工信息 toEditEmployee
	@RequestMapping(value = "/toEditEmployee", method = { RequestMethod.GET, RequestMethod.POST })
	public String toEditEmployee(Model model, String eno) {
		List<Department> departments = departmentService.selectAll();
		Comployee comployee = comployeeService.selectByPrimaryKey(eno);

		model.addAttribute("departments", departments);
		model.addAttribute("employee", comployee);
		return "employee/employee_edit";
	}

	// editEmployeeInfo
	@ResponseBody
	@RequestMapping(value = "/editEmployeeInfo", method = { RequestMethod.GET, RequestMethod.POST })
	public String editEmployeeInfo(Model model, @RequestBody Comployee comployee) {
		try {
			comployeeService.updateByPrimaryKeySelective(comployee);
		} catch (Exception e) {
			return "error";
		}
		return "/user_list";
	}

	@RequestMapping(value = "/deleteEmployee", method = { RequestMethod.GET, RequestMethod.POST })
	public String deleteEmployee(Model model, String eno) {
		comployeeService.deleteByPrimaryKey(eno);
		return "redirect:/user_list";
	}

	// toupdatepwd
	@RequestMapping(value = "/toupdatepwd", method = { RequestMethod.GET, RequestMethod.POST })
	public String toupdatepwd(Model model, HttpSession session) {

		return "user_info/updatepwd";
	}

	// updatepwd
	@ResponseBody
	@RequestMapping(value = "/updatepwd", method = { RequestMethod.POST })
	public String updatepwd(Model model, HttpSession session, @RequestBody Map<String, String> dataMap) {
		Assert.notEmpty(dataMap, "参数异常:212");
		String newpwd = dataMap.get(MenuEnum.PasswordEnum.Parm1.getK());
		String oldpwd = dataMap.get(MenuEnum.PasswordEnum.Parm2.getK());
		String renewpwd = dataMap.get(MenuEnum.PasswordEnum.Parm3.getK());
		String username = dataMap.get(MenuEnum.PasswordEnum.Parm4.getK());
		String od = userInfoService.selectByPrimaryKey(username).getPwd();
		if (od.equals(oldpwd) && newpwd.equals(renewpwd)) {
			UserInfo ui = new UserInfo();
			ui.setUsername(username);
			ui.setPwd(newpwd);
			userInfoService.updateByPrimaryKeySelective(ui);
			model.addAttribute("err", "恭喜你，修改成功！！！");
			return "/user_info/updatepwd";

		}
		model.addAttribute("err", "修改失败！！！");
		return "error";
	}

	// 资产信息
	@RequestMapping(value = "/zc_list", method = { RequestMethod.GET, RequestMethod.POST })
	public String zc_list(Model model, HttpSession session) {
		model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectAll()));
		return "zcinfo/zcinfo_list";
	}

	// to_zcinfo_add
	@RequestMapping(value = "/to_zcinfo_add", method = { RequestMethod.GET, RequestMethod.POST })
	public String to_zcinfo_add(Model model, HttpSession session) {

		return "zcinfo/zcinfo_add";
	}

	// addzc
	@RequestMapping(value = "/addzc", method = { RequestMethod.POST })
	@ResponseBody
	public String addzc(Model model, HttpSession session, @RequestBody ZcInfo zcInfo) {

		try {
			zcInfoService.insertSelective(zcInfo);
		} catch (Exception e) {
			return "error";
		}
		return "/zc_list";
	}

	// updateAssets?zc_id=${item.zcId}
	@RequestMapping(value = "/updateAssets", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateAssets(Model model, HttpSession session, String zc_id) {
		model.addAttribute("zs", zcInfoService.selectByPrimaryKey(zc_id));
		return "zcinfo/zcinfo_edit";
	}

	// editzc
	@RequestMapping(value = "/editzc", method = { RequestMethod.GET, RequestMethod.POST })
	public String editzc(Model model, HttpSession session, ZcInfo zcInfo) {
		zcInfoService.updateByPrimaryKeySelective(zcInfo);
		return "redirect:/zc_list";
	}

	// deleteAssets
	@RequestMapping(value = "/deleteAssets", method = { RequestMethod.GET, RequestMethod.POST })
	public String deleteAssets(Model model, HttpSession session, String zc_id) {
		zcInfoService.deleteByPrimaryKey(zc_id);
		return "redirect:/zc_list";
	}

	// 折旧
	@RequestMapping(value = "/zczj", method = { RequestMethod.GET, RequestMethod.POST })
	public String zczj(Model model, HttpSession session) {
		model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectAll()));
		return "zcinfo/zcinfo_list1";
	}

	@RequestMapping(value = "/updateAssets1", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateAssets1(Model model, HttpSession session, String zc_id) {
		model.addAttribute("zs", zcInfoService.selectByPrimaryKey(zc_id));
		return "zcinfo/zcinfo_edit1";
	}

//	最后一个模块的修改
	@RequestMapping(value = "/editzc1", method = { RequestMethod.POST })
	@ResponseBody
	public String editzc1(Model model, HttpSession session, @RequestBody ZcInfo zcInfo) {
		zcInfoService.updateByPrimaryKeySelective(zcInfo);
		return "/zczj";
	}

	// chaxun
	@RequestMapping(value = "/chaxun", method = { RequestMethod.GET, RequestMethod.POST })
	public String chaxun(Model model, HttpSession session, String dept, String type) {
		if (dept.equals("0") && type.equals("0")) {
			model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectAll()));
		} else if (!dept.equals("0") && type.equals("0")) {
			model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectByDept(dept)));
		} else if (dept.equals("0") && !type.equals("0")) {
			model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectByType(type)));
		} else {
			ZcInfo zi = new ZcInfo();
			zi.setZcBzxx(dept);
			zi.setZcType(type);
			model.addAttribute("zc_list", JSON.toJSONString(zcInfoService.selectByTypeAndDept(zi)));
		}

		return "zcinfo/zcinfo_list";
	}

	// chaxun
	@RequestMapping(value = "/chauneno", method = { RequestMethod.GET, RequestMethod.POST })
	public String chauneno(Model model, HttpSession session, String dept, String eno) {
		if (dept.equals("0") && (eno == null || eno.equals(""))) {
			model.addAttribute("comployees", JSON.toJSONString(comployeeService.selectAll()));
		} else if (!dept.equals("0") && (eno == null || eno.equals(""))) {
			model.addAttribute("comployees", JSON.toJSONString(comployeeService.selectByPrimaryKey1(dept)));
		} else if (dept.equals("0") && !(eno == null || eno.equals(""))) {
			model.addAttribute("comployees", JSON.toJSONString(comployeeService.selectByPrimaryKey2(eno)));
		} else {
			Comployee c = new Comployee();
			c.setComployeeNo(eno);
			c.setDept(dept);
			model.addAttribute("comployees", JSON.toJSONString(comployeeService.selectByPrimaryKey3(c)));
		}

		return "employee/employee_list";
	}

	// 借还管理 jiehuan
	@RequestMapping(value = "/jiehuan", method = { RequestMethod.GET, RequestMethod.POST })
	public String jiehuan(Model model, HttpSession session) {
		String code = String.valueOf(session.getAttribute("code"));
		List<ZcInout> dataList = zcInoutService.selectAll(code);
		model.addAttribute("jihuans", JSON.toJSONString(dataList));
		model.addAttribute("uid", code);
		model.addAttribute("zc_list", zcInfoService.selectAll());

		return "zc_inout/zc_in_out";
	}

	// lendZC
	@RequestMapping(value = "/lendZC", method = { RequestMethod.GET, RequestMethod.POST })
	public String lendZC(Model model, HttpSession session, ZcInout zcio) {
		ZcInout z = zcInoutService.selectByzc(zcio.getZcId());
		if (z == null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			zcio.setOutTime(sdf.format(new Date()));
			String code = String.valueOf(session.getAttribute("code"));
			zcio.setComployeeNo(code);
			zcInoutService.insertSelective(zcio);
			return "redirect:/jiehuan";
		}
		model.addAttribute("error", "<script>alert('改设备已被借出！！操作失败！！');window.location.href='/jiehuan'</script>");
		return "zc_inout/zc_in_out";
	}

	// backZC
	@RequestMapping(value = "/backZC", method = { RequestMethod.GET, RequestMethod.POST })
	public String backZC(Model model, HttpSession session, Integer inout_no) {
		ZcInout zcio = new ZcInout();
		zcio.setInoutNo(inout_no);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		zcio.setBackTime(sdf.format(new Date()));
		zcInoutService.updateByPrimaryKeySelective(zcio);
		return "redirect:/jiehuan";
	}

	// 001 tableData
	@RequestMapping(value = "/jiehuan1", method = { RequestMethod.GET, RequestMethod.POST })
	public String jiehuan1(Model model, HttpSession session) {

		List<ZcInout> tableData = zcInoutService.selectAll1();
		model.addAttribute("jihuans",
				StringUtils.isEmpty(JSON.toJSONString(tableData)) ? "[]" : JSON.toJSONString(tableData));
		model.addAttribute("zc_list", zcInfoService.selectAll());
		return "zc_inout/zc_in_out1";
	}

	// 001 tableData Ajax
	@RequestMapping(value = "/inoutchaxun", method = { RequestMethod.GET, RequestMethod.POST })
	public String inoutchaxun(Model model, HttpSession session, @RequestParam String zcId) {
		if (!StringUtils.isEmpty(zcId)) {
			List<ZcInout> tableData = zcInoutService.selectAll2(zcId);
			if (!CollectionUtils.isEmpty(tableData)) {
				String jsonData = JSON.toJSONString(tableData);
				model.addAttribute("jihuans", jsonData);
			} else {
				model.addAttribute("jihuans", "[]");
			}
		}

		model.addAttribute("zc_list", zcInfoService.selectAll());
		return "zc_inout/zc_in_out1";
	}

	// genghuan
	@RequestMapping(value = "/genghuan", method = { RequestMethod.GET, RequestMethod.POST })
	public String genghuan(Model model, HttpSession session) {
		return "user_info/genghuan";
	}

	@ResponseBody
	@RequestMapping(value = "/genghuan1", method = { RequestMethod.GET, RequestMethod.POST })
	public String genghuan1(Model model, HttpSession session, MultipartFile file) {
		String path = "D:\\Users\\images\\";
		new File(path).mkdirs();
		String filename = "0000.gif";
		File file0 = new File(path + filename);
		if (file0.exists()) {
			file0.delete();
		}
		try {
			file.transferTo(new File(path + filename));
		} catch (IOException e) {
			e.printStackTrace();
		}
		model.addAttribute("success", "<script>alert('上传成功，重启服务生效！！');</script>");
		Map<String, String> map = new HashMap<String, String>();
		map.put("src", path + filename);
		return JSON.toJSONString(map);
	}

	// 去注册
	@RequestMapping(value = "/toreg", method = { RequestMethod.GET, RequestMethod.POST })
	public String toreg(Model model, HttpSession session) {
		return "login/reg";
	}

	@RequestMapping(value = "/reg", method = { RequestMethod.GET, RequestMethod.POST })
	public String reg(Model model, HttpSession session, UserInfo ui, String password) {
		
		if (password.equals(ui.getPwd())) {
			UserInfo ui1 = userInfoService.selectByPrimaryKey(ui.getUsername());
			if (ui1 == null) {
				if (ui.getCompetence().equals("用户")) {
					// 借还管理,借还查询,更换背景
					ui.setMenu("借还管理,借还查询,更换背景");
				}
				if (ui.getCompetence().equals("设备管理员")) {
					// 借还管理,借还查询,更换背景
					ui.setMenu("设备管理,资产折旧");
				}
				if (ui.getCompetence().equals("系统管理员")) {
					// 借还管理,借还查询,更换背景
					ui.setMenu("权限管理,用户管理,数据统计");
				}
				userInfoService.insertSelective(ui);
				model.addAttribute("err", "注册成功！");
				return "redirect:/";
			}
		}

		model.addAttribute("err", "注册失败！");

		return "login/reg";
	}

}
